package leetcode.weekly.week317;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

//Solution2Test
public class Solution2 {

	public List<List<String>> mostPopularCreator(String[] creators, String[] ids, int[] views) {
		int n = creators.length;
		Map<String, Long> total = new HashMap<>();
		long max = -1;
		for (int i = 0; i < n; i++) {
			String c = creators[i];
			long view = 1l * views[i];
			long cur = 1l * total.getOrDefault(c, 0l) + view;
			max = Math.max(max, cur);
			total.put(c, cur);
		}
		Set<String> cs = new HashSet<>();
		Map<String, List<Object>> maxs = new HashMap<>();
		for (Map.Entry<String, Long> entry : total.entrySet()) {
			if (entry.getValue() == max) {
				cs.add(entry.getKey());
				maxs.put(entry.getKey(), new ArrayList<>());
			}
		}
		List<List<String>> ans = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			String c = creators[i];
			if (cs.contains(c)) {
				List<Object> m = maxs.get(c);
				if (m.isEmpty()) {
					m.add(ids[i]);
					m.add(views[i]);
				} else {
					if (views[i] > Integer.valueOf(m.get(1).toString())
							|| (views[i] == Integer.valueOf(m.get(1).toString())
									&& ids[i].compareTo(m.get(0).toString()) < 0)) {
						List<Object> list = new ArrayList<>();
						list.add(ids[i]);
						list.add(views[i]);
						maxs.put(c, list);
					}
				}
			}
		}
		for (Map.Entry<String, List<Object>> entry : maxs.entrySet()) {
			ans.add(Arrays.asList(new String[] { entry.getKey(), entry.getValue().get(0).toString() }));
		}
		return ans;
	}

//	public static void main(String[] args) {
//		String a = "a";
//		String b = "a";
//		System.out.println(b.compareTo(a));
//		System.out.println(a.compareTo(b));
//		System.out.println(Long.MAX_VALUE);
//	}

}
